<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var data = [{
            id: 1,
            name: '家电',
            goods: [{
                id: 11,
                gname: '冰箱',
                goods: [{
                    id: 111,
                    gname: '海尔'
                }, {
                    id: 222,
                    gname: '美的'
                }]
            }, {
                id: 12,
                gname: '洗衣机'
            }]
        }, {
            id: 2,
            name: '服饰'
        }]
        //我们想要输入id号，就可以返回的数据对象
        //利用foEach取遍历数组中的每个对象
        function getId(json, id) {
            var o = {} //声明一个保存对象
            json.forEach(function (item) {
                // console.log(item); 两个数组元素
                if (item.id == id) {
                    // console.log(item);
                    o = item
                    //想要的到里层的数据11 12利用函数递归
                    //里面应该有goods数组，且数组长度不为0
                } else if (item.goods && item.goods.length > 0) {
                    o = getId(item.goods, id);

                }
            })
            return o;

        }
        console.log(getId(data, 1));
        console.log(getId(data, 2));
        console.log(getId(data, 11));
        console.log(getId(data, 12));
        console.log(getId(data, 111));



    </script>
</body>

</html>